package com.helloworld.chat.dao.impl;

import com.helloworld.chat.dao.UserDao;
import com.helloworld.chat.entity.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by xdzy on 2017/6/28.
 */
@Repository
public class UserDaoImpl implements  UserDao {
    private SessionFactory sessionFactory;
    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void insert(User user) {
        sessionFactory.getCurrentSession().save(user);
    }

    @Override
    public User getUser(int id) {
        return sessionFactory.getCurrentSession().get(User.class,id);
    }

    @Override
    public User getUser(String username) {
        String hql="from User where username=:u";
        return sessionFactory.getCurrentSession().createQuery(hql,User.class)
                .setParameter("u",username).uniqueResult();
    }

    @Override
    public List<User> getUserList() {
        return sessionFactory.getCurrentSession().createQuery("from User",User.class)
                .list();
    }

    @Override
    public User findByUserName(String username) {
        // TODO Auto-generated method stub
        String hql="from User where username=:u";
        User user= sessionFactory.getCurrentSession().createQuery(hql,User.class)
                .setParameter("u",username).uniqueResult();
        if(user!=null)
        {
            return user;
        }
        return null;
    }

    @Override
    public void register(User user) {
        // TODO Auto-generated method stub

        sessionFactory.getCurrentSession().save(user);

    }

    @Override
    public void update(User user) {
        // TODO Auto-generated method stub
        sessionFactory.getCurrentSession().update(user);
    }

    @Override
    public User findById(int uid) {
        // TODO Auto-generated method stub

        return sessionFactory.getCurrentSession().get(User.class, uid);
    }
}
